<template>
  <el-card>
    <div class="flex justify-between items-center mb-4">
      <h2>课题管理</h2>
      <el-button type="primary" @click="$router.push('/enterprise/projects/create')">
        <el-icon><Plus /></el-icon> 发布新课题
      </el-button>
    </div>

    <el-table v-loading="loading" :data="topicList" border>
      <el-table-column prop="title" label="课题名称" width="250"></el-table-column>
      <el-table-column prop="category" label="研究方向"></el-table-column>
      <el-table-column prop="deadline" label="截止日期" :formatter="formatDate"></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        :formatter="formatStatus"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <!--
          <el-button
            size="small"
            @click="$router.push(`/enterprise/projects/edit/${scope.row.id}`)"
            v-if="scope.row.status === 'open'"
          >
            编辑
          </el-button>
          -->
          <el-button
            size="small"
            type="success"
            @click="$router.push(`/enterprise/applications?topicId=${scope.row.id}`)"
          >
            查看申请
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-if="scope.row.status === 'open'"
          >
            删除课题
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="total"
        @current-change="fetchTopics"
        @size-change="fetchTopics"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  getMyProjects,
  deleteProject,
  ProjectStatus
} from '@/api/enterpriseTypes';

const topicList = ref<any[]>([]);
const loading = ref(true);
const total = ref(0);

const pagination = ref({
  page: 1,
  size: 10
});

// 获取课题列表
const fetchTopics = async () => {
  loading.value = true;
  try {
    const res = await getMyProjects({
      page: pagination.value.page,
      size: pagination.value.size
    });
    topicList.value = res.data || [];
    total.value = res.total || 0;
  } catch (error) {
    ElMessage.error('获取课题列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (row: any, column: any, cellValue: string) => {
  return cellValue ? new Date(cellValue).toLocaleDateString() : '';
};

// 格式化状态显示
const formatStatus = (row: any, column: any, cellValue: string) => {
  const statusMap: Record<string, string> = {
    [ProjectStatus.Open]: '开放',
    [ProjectStatus.Closed]: '已关闭',
    [ProjectStatus.InProgress]: '进行中',
    [ProjectStatus.Completed]: '已完成'
  };
  return statusMap[cellValue] || cellValue;
};

// 删除课题
const handleDelete = async (id: number) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这个课题吗？删除后无法恢复，请谨慎操作。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    );
    
    // 用户确认后执行删除
    const response = await deleteProject(id);
    ElMessage.success('课题删除成功');
    fetchTopics();
  } catch (error: any) {
    // 如果是用户取消操作，不显示错误信息
    if (error === 'cancel') {
      return;
    }
    
    // 处理具体的错误响应
    const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
    ElMessage.error(errorMessage);
  }
};

onMounted(fetchTopics);
</script>
